﻿using Microsoft.Silverlight.Testing.Harness;
using Microsoft.Silverlight.Testing.UnitTesting.Harness;
using Ninject.Core;
using Odin.Contracts.Data;
using Odin.Silverlight.RemoteSessionManager;

namespace Odin.Silverlight
{
	public class UnitTestResultLogProvider : LogProvider
	{
		[Inject]
		public IRemoteSessionManager RemoteSessionManager { get; set; }

		public Session Session { get; set; }

		private Result GetResult(ScenarioResult scenarioResult)
		{
			switch( scenarioResult.Result )
			{
				case TestOutcome.Passed:
					{
						return Result.Passed;
					}
				case TestOutcome.Inconclusive:
					{
						return Result.Inconlusive;
					}
				case TestOutcome.Failed:
					{
						return Result.Failed;
					}
			}

			return Result.NotRun;
		}


		protected override void ProcessRemainder(LogMessage message)
		{
			switch (message.MessageType)
			{
				case LogMessageType.TestResult:
					{
						if (message.Decorators.ContainsKey(UnitTestLogDecorator.ScenarioResult))
						{
							var result = message.Decorators[UnitTestLogDecorator.ScenarioResult] as ScenarioResult;

							if (null != result)
							{
								var namespaceName = result.TestClass.Type.Namespace;
								var className = result.TestClass.Name;
								var methodName = result.TestMethod.Name;
								var method = new Method
								             	{
								             		Namespace = namespaceName,
								             		Class = className,
								             		MethodName = methodName
								             	};


								method.Result = GetResult(result);
								if( null != result.Exception )
								{
									method.Message = result.Exception.Message;
									method.StackTrace = result.Exception.StackTrace;
								}

								RemoteSessionManager.BeginReportMethod(Session, method,
								                                       a => RemoteSessionManager.EndReportMethod(a), null);
							}
						}
						break;
					}
			}

		}


	}
}
